package com.demo2do.mobile.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.demo2do.core.persistence.GenericDaoSupport;
import com.demo2do.mobile.entity.FoundationRecord;
import com.demo2do.mobile.entity.FoundationStat;
import com.demo2do.mobile.service.FoundationService;

/**
 * 
 * @author mohanlan
 *
 */
@Service("foundationService")
public class FoundationServiceImpl implements FoundationService {

	@Autowired
	private GenericDaoSupport genericDaoSupport;
	
	/*
	 * (non-Javadoc)
	 * @see com.demo2do.mobile.service.FoundationService#stat()
	 */
	public FoundationStat stat() {
		return genericDaoSupport.searchForObject("SELECT new com.demo2do.mobile.entity.FoundationStat(Count(*), SUM(amount)) FROM FoundationRecord WHERE disabled = false", FoundationStat.class);
	}

	/*
	 * (non-Javadoc)
	 * @see com.demo2do.mobile.service.FoundationService#createOrUpdate(com.demo2do.mobile.entity.FoundationRecord)
	 */
	public void createOrUpdate(FoundationRecord foundationRecord) {
		
		String mobile = foundationRecord.getMobile();
		
		FoundationRecord exitFoundation = this.get(mobile);
		
		if (exitFoundation == null) {
			genericDaoSupport.save(foundationRecord.init());
			
		} else {
			
			String name = foundationRecord.getName();
			int amount = foundationRecord.getAmount();
			
			genericDaoSupport.update(exitFoundation.edit(mobile, name, amount));
		}
	}

	/*
	 * (non-Javadoc)
	 * @see com.demo2do.mobile.service.FoundationService#load(java.lang.String)
	 */
	public FoundationRecord load(String mobile) {
		return this.get(mobile);
	}
	
	/**
	 * 
	 * @param mobile
	 * @return
	 */
	protected FoundationRecord get(String mobile) {
		return genericDaoSupport.searchForObject("FROM FoundationRecord WHERE mobile = :mobile", "mobile", mobile, FoundationRecord.class);
	}

}
